<script setup lang="ts">
import { ref, onMounted, watch } from 'vue';
import { useRouter } from 'vue-router';
import dragVerify from '@/components/dragVerify/dragVerify.vue';
import { ElMessage } from "element-plus";
import md5 from "md5";
import { Get, Post } from "@/utils/api";
import { validateEmail } from '@/utils/utils'; // 导入 validateEmail 函数

const router = useRouter();
const email = ref('');
const schoolId = ref<string | null>(null);
const staffName = ref('');
const serialNo = ref('');
const username = ref('');
const password = ref('');
const verifyPassword = ref('');
const flag = ref('1')
const schoolList = ref<string | null>(null);
const options = ref<Array<{ label: string; value: string }>>([]);
const form = ref({ isVerifyPass: false, passwordVerify: false });
import CryptoJS from 'crypto-js';

watch(verifyPassword, (newVal) => {
  if (password.value) {
    if (md5(password.value) === md5(newVal)) {
      form.value.passwordVerify = true;
      ElMessage.success("两次密码一致");
    } else {
      form.value.passwordVerify = false;
      ElMessage.error("两次密码不一致");
    }
  } else {
    form.value.passwordVerify = false;
    ElMessage.error("请输入密码");
  }
});

async function getSchool() {
  try {
    const response = await Get('/school/listAll');
    if (response.data && Array.isArray(response.data)) {
      options.value = response.data.map((school: { id: string; name: string }) => ({
        value: school.id,
        label: school.name
      }));
    }
  } catch (error) {
    ElMessage.error("无法获取学校列表");
  }
}

onMounted(() => {
  getSchool();
});

function goLoginIndex() {
  router.push('/login/index');
}

function goEmailIndex() {
  router.push('/login-email/index');
}

async function register() {
  // 检查表单验证状态
  if (form.value.isVerifyPass && form.value.passwordVerify) {
    if (!validateEmail(email.value)) {
      return ElMessage.error('无效的邮箱地址，请检查并重新输入。');
    }

    // 加密密钥
    const key = CryptoJS.enc.Utf8.parse("smartschool320..");

    // 加密用户名和密码
    const encryptedEmail = CryptoJS.AES.encrypt(CryptoJS.enc.Utf8.parse(email.value), key, {
      mode: CryptoJS.mode.ECB,
      padding: CryptoJS.pad.Pkcs7
    }).toString();

    const encryptedUsername = CryptoJS.AES.encrypt(CryptoJS.enc.Utf8.parse(username.value), key, {
      mode: CryptoJS.mode.ECB,
      padding: CryptoJS.pad.Pkcs7
    }).toString();

    const encryptedPassword = CryptoJS.AES.encrypt(CryptoJS.enc.Utf8.parse(password.value), key, {
      mode: CryptoJS.mode.ECB,
      padding: CryptoJS.pad.Pkcs7
    }).toString();

    // 创建请求数据
    const data = {
      staffName: staffName.value,
      username: encryptedUsername,
      password: encryptedPassword,
      email: encryptedEmail,
      schoolId: schoolList.value,
      serialNo: serialNo.value,
      flag: flag.value
    };

    try {
      const response = await Post('/user/register', data);
      if (response.success){
        ElMessage.success(response.message);
        goLoginIndex();
      }else {
        ElMessage.error(response.message);
      }

    } catch (error) {
      ElMessage.error('注册失败，请重试');
    }
  } else {
    ElMessage.error('请填写正确');
  }
}
</script>

<template>
  <div class="input-container">
    <span style="margin-bottom: 10px; color: black; font-size: 20px"><b>注 册</b></span>
    <el-select
        v-model="schoolList"
        filterable
        clearable
        placeholder="请选择就读院校"
        style="width: 290px; height: 50px; margin-bottom: 10px; font-size: 18px;"
    >
      <el-option
          v-for="item in options"
          :key="item.value"
          :label="item.label"
          :value="item.value"
      />
    </el-select>
    <el-input
        v-model="staffName"
        style="width: 290px; height: 50px; margin-bottom: 10px; font-size: 18px;"
        placeholder="请输入真实姓名"
        clearable
        aria-required="true"
    />
    <el-input
        v-model="serialNo"
        style="width: 290px; height: 50px; margin-bottom: 10px; font-size: 18px;"
        placeholder="请输入学号/工号"
        clearable
        aria-required="true"
    />
    <el-input
        v-model="email"
        style="width: 290px; height: 50px; margin-bottom: 10px; font-size: 18px;"
        placeholder="请输入邮箱"
        clearable
    />
    <el-input
        v-model="username"
        style="width: 290px; height: 50px; margin-bottom: 10px; font-size: 18px;"
        placeholder="请输入账号"
        clearable
    />
    <el-input
        v-model="password"
        style="width: 290px; height: 50px; margin-bottom: 10px; font-size: 18px;"
        type="password"
        placeholder="请输入密码"
        show-password
    />
    <el-input
        v-model="verifyPassword"
        style="width: 290px; height: 50px; margin-bottom: 10px; font-size: 18px;"
        type="password"
        placeholder="请再次输入密码"
        show-password
    />
    <el-radio-group v-model="flag" style="width: 290px; height: 50px; margin-bottom: 10px; font-size: 18px;">
      <el-radio value="1" border>学生</el-radio>
      <el-radio value="0" border>老师</el-radio>
    </el-radio-group>
    <div class="content">
      <dragVerify v-model:value="form.isVerifyPass"></dragVerify>
    </div>
    <el-button type="primary" class='register-button' @click="register" plain :disabled="!form.isVerifyPass">注册</el-button>

    <div class="footer">
      <button @click="goLoginIndex">返回账号登录</button>
      <button @click="goEmailIndex">返回邮箱登录</button>
    </div>

  </div>
</template>

<style scoped lang="scss">
.input-container {
  border: 2px solid #ccc;
  padding: 10px;
  border-radius: 15px;
  width: 400px;
  height: 550px;
  margin: 0 auto;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  background-color: rgb(255, 255, 255);
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

.content {
  margin-bottom: 10px;
}

.footer {
  display: flex;
  justify-content: space-between;
  padding: 10px;
  width: 290px;
}

.register-button {
  width: 290px;
  height: 40px;
  font-size: 18px;
}
</style>